package cn.fintecher.pangolin.service.common.web;

import cn.fintecher.pangolin.common.enums.BaseStatus;
import cn.fintecher.pangolin.common.exception.BadRequestException;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.response.LoginResponse;
import cn.fintecher.pangolin.common.utils.Constants;
import cn.fintecher.pangolin.entity.mysql.SysParam;
import cn.fintecher.pangolin.service.common.client.OperatorCommonClient;
import cn.fintecher.pangolin.service.common.model.request.AddTaskRecorderRequest;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * @Author : wangyannong
 * @Description :语音卡
 * @Date : 2019/11/28 16:45
 */
@RestController
@RequestMapping(value = "/api/beauPhoneController")
@Api(value = "呼叫相关接口", description = "呼叫相关接口")
public class BeauPhoneController {
    Logger logger = LoggerFactory.getLogger(BeauPhoneController.class);

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private OperatorCommonClient operatorCommonClient;



    @PostMapping("/call")
    @ApiOperation(value = "开始电话呼叫", notes = "开始电话呼叫")
    public ResponseEntity<Map<String, String>> call(@RequestBody AddTaskRecorderRequest request,
                                                    @RequestHeader(value = "X-UserToken") String token) {
        ResponseEntity<LoginResponse> userByToken = operatorCommonClient.getUserByToken(token);
        if (Objects.isNull(userByToken.getBody())) {
            throw new BadRequestException(null, "user", "this user is not login");
        }

        UserModel user = userByToken.getBody().getUserModel();
        if(Objects.isNull(user.getChannelNo())){
            throw  new BadRequestException(null,"call","channelNo.is.empty");
        }
        SysParam param = restTemplate.getForEntity("http://manage-service/api/sysParamController/querySysParamByCode?code=" + Constants.PHONE_BF_URL, SysParam.class).getBody();
        if(Objects.isNull(param)){
            throw  new BadRequestException(null,"call","sysParam.is.empty");
        }
        if(BaseStatus.OFF.equals(param.getStatus())){
            throw  new BadRequestException(null,"call","beauphone.is.off");
        }
        SysParam sysparam = restTemplate.getForEntity("http://manage-service/api/sysParamController/querySysParamByCode?code=" + Constants.PHONE_PHONE_CODE, SysParam.class).getBody();
        if(Objects.isNull(sysparam)){
            throw  new BadRequestException(null,"call","sysParam.is.empty");
        }
        if(BaseStatus.OFF.equals(sysparam.getStatus())){
            throw  new BadRequestException(null,"call","beauphone.is.off");
        }
        RestTemplate template = new RestTemplate();
        String sysValue = param.getValue();
        String mobileno = request.getCallee();
        try {
            String zoneno = getZoneno(sysValue, mobileno);
            //如果外地号码，号码前+ 0
            if (zoneno != null && !zoneno.equals(sysparam.getValue())) {//去根据区号判断是否为本地号码
                mobileno = "0" + mobileno;
            }
        }catch (Exception e){
            throw  new BadRequestException(null,"call","zoneno.is.error");
        }
        //template.getForEntity("http://" + sysValue + "/stopdial?channelno=" + user.getChannelNo(),String.class);//拨打电话钱先停止其他的呼叫
        ResponseEntity entity = template.getForEntity("http://" + sysValue + "/startdialpassive?channelno=" + user.getChannelNo() + "&telephoneno=" + mobileno, String.class);
        Map paramMap = new HashMap();

        if (entity.hasBody()) {
            String fileStr = entity.getBody().toString();
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.parseObject(URLDecoder.decode(URLEncoder.encode(fileStr, "UTF-8").replaceAll("%5C", "//"), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw  new BadRequestException(null,"call","json.is.error");
            }
            String status = jsonObject.getString("status");
            if(status.equals("516")){
                throw  new BadRequestException(null,"call","beauphone.status.error.init");
            }else if(status.equals("517")){
                throw  new BadRequestException(null,"call","beauphone.status.error.number");
            }else if(status.equals("518")){
                throw  new BadRequestException(null,"call","beauphone.status.error.channel");
            }else if(status.equals("519")){
                throw  new BadRequestException(null,"call","beauphone.status.error.dire");
            }else if(status.equals("520")){
                throw  new BadRequestException(null,"call","beauphone.status.error.record");
            }else if(status.equals("200")){
                paramMap.put("filepath",jsonObject.get("filepath") );//
                paramMap.put("filename",jsonObject.get("filename") );//
                return ResponseEntity.ok().body(paramMap);
            }else{
                return ResponseEntity.badRequest().body(null);
            }
        }
        return ResponseEntity.badRequest().body(null);
    }

    private String getZoneno(String sysValue, String mobileno) throws Exception{
        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
        List<HttpMessageConverter<?>> converterList = template.getMessageConverters();
        HttpMessageConverter<?> converterTarget = null;
        for (HttpMessageConverter<?> item : converterList) {
            if (item.getClass() == StringHttpMessageConverter.class) {
                converterTarget = item;
                break;
            }
        }

        if (converterTarget != null) {
            converterList.remove(converterTarget);
        }
        HttpMessageConverter<?> converter = new StringHttpMessageConverter(Charset.forName("GB2312"));
        converterList.add(converter);
        //查询手机归属
        ResponseEntity<String> entity = template.exchange("http://" + sysValue + "/gethomelocation?mobileno=" + mobileno, org.springframework.http.HttpMethod.GET, requestEntity, String.class);
        String fileStr = entity.getBody().toString();
        JSONObject jsonObject = JSONObject.parseObject(fileStr);
        String zoneno = jsonObject.getString("固话区号");
        return zoneno;
    }
}
